package com.dx.VegetableOxygenBarBackEnd.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dx.VegetableOxygenBarBackEnd.model.domain.entity.User;
import com.dx.VegetableOxygenBarBackEnd.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 缓存预热任务
 */
@Component
@Slf4j

public class PreCacheJob {
    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private RedissonClient redissonClient;


    //重点用户
    List<Long> mainList = Arrays.asList(2l);

    @Scheduled(cron = "0 44 11 * * ?")
    public void doCacheRecommendUser() {
        RLock lock = redissonClient.getLock("shucai:precachejob:docache:lock");
        boolean isGetLock = false;
        try {
            //只有一个线程获取锁
            //waitTime  等待时间，允许等待的时间，超出就不等了
            //leaseTime 过期时间
            isGetLock = lock.tryLock(0, 30000L, TimeUnit.MILLISECONDS);
            if (isGetLock) {
                for (Long userId : mainList) {
                    ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
                    String redisKey = String.format("shucai:user:recommend:%s", userId);
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    Page<User> userPage = userService.page(new Page<>(1, 20), queryWrapper);
                    try {
                        valueOperations.set(redisKey, userPage, 30000, TimeUnit.MILLISECONDS);
                    } catch (Exception e) {
                        log.error("redis set key error", e);
                    }
                }
            }
        } catch (InterruptedException e) {
            log.error("PreCacheJob redisson doCacheRecommendUser error",e);
        } finally {
            if(lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        }
    }
}
